package com.dyh.quickdemozwei.MapUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dyh.quickdemozwei.withdraw.M;
import com.google.common.collect.ImmutableMultimap;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Map;

public interface MapUtils {

    /*
    不会因为val为空把旧值删除
    * a->1     a->11      a->11
    * b->2                b->2
     *

    * */
    static Map<?,Object> incMegre(Map<?,Object> oldMap,Map<?,Object>  newMap){

        if (CollectionUtils.isEmpty(oldMap))
            return newMap;
        Map<Object,Object> result = new HashMap<>();


        for (Map.Entry<?, Object> entry : oldMap.entrySet()) {
            Object key = entry.getKey();
            Object oldVal = entry.getValue();
            Object newVal = newMap.get(key);
            if (newVal == null){
                result.put(key,oldVal);
                continue;
            }

            if (newVal instanceof JSONObject)
                result.put(key,incMegre((Map)oldVal,(Map)newVal));

            result.put(key,newVal);
        }

        for (Map.Entry<?, Object> entry : newMap.entrySet()) {
            Object key = entry.getKey();
            Object newVal  = entry.getValue();
            Object oldVal = oldMap.get(key);
            if (oldVal==null)
                result.put(key,newVal);
        }

        return result;

    }

    public static void main(String[] args) {

        Map<String,Object> oldMap = new HashMap<>();
        oldMap.put("a",1);
        oldMap.put("b",2);
        JSONObject joo = new JSONObject();
        joo.put("A",11);
        joo.put("B",22);
        oldMap.put("j",joo);

        Map<String,Object> newMap = new HashMap<>();
        newMap.put("a",2);
        newMap.put("c",6);
        JSONObject jon = new JSONObject();
        jon.put("A",22);
        jon.put("c",33);
        newMap.put("j",jon);


        System.out.println(JSON.toJSON(oldMap));
        System.out.println(JSON.toJSON(newMap));
        System.out.println(JSON.toJSON(incMegre(oldMap,newMap)));



//        Map m1 = new HashMap<Integer,Object> ();
//        m1.put(1,"11");
//
//        Map<String,Object> m2 = (Map<String,Object>)m1;
//
//        Object r = m2.get(1);
//
//        System.out.println();
    }
}
